package xiaoa.java.log;

/**
 * 日志工具类
 * 
 * @author lkc
 * @date 2017年8月9日 上午10:49:10
 * @version V1.0
 *
 */
public class LogUtils {

	// 保存线程中的事物id 以及其他关于日志属性 保证在整个系统中事物id始终保持一致
	private static ThreadLocal<Object[]> logThreadLocal = new ThreadLocal<Object[]>();

	/**
	 * 事物idkey
	 */
	private static final int TID_KEY = 0;

	/**
	 * http请求次数 计数器
	 */
	private static final int HTTP_COUNT_KEY = 1;

	/**
	 * 计数器空值状态
	 */
	public static final String HTTP_COUNT_EMPTY = "0000";

	/**
	 * 设置值
	 * 
	 * @Title: setValue
	 * @param i
	 * @param value
	 * @author lkc
	 */
	private static void setValue(int i, Object value) {
		setValue(i, value, false);
	}

	/**
	 * 设置值
	 * 
	 * @Title: setValue
	 * @param i
	 * @param value
	 * @param clear
	 *            是否清除
	 * @author lkc
	 */
	private static void setValue(int i, Object value, boolean clear) {
		if (value == null) {
			return;
		}
		Object[] values = logThreadLocal.get();
		if (values == null || clear) {
			values = new Object[i + 1];
			logThreadLocal.set(values);
		} else if (values.length <= i) {
			Object[] valuesTemp = new Object[i + 1];
			System.arraycopy(values, 0, valuesTemp, 0, values.length);
			values = valuesTemp;
			logThreadLocal.set(values);
		}
		values[i] = value;
	}

	/**
	 * 获取值
	 * 
	 * @Title: getValue
	 * @param i
	 * @return
	 * @author lkc
	 */
	@SuppressWarnings("unchecked")
	private static <T> T getValue(int i) {
		Object[] values = logThreadLocal.get();
		if (values == null || i >= values.length) {
			return null;
		}
		return (T) values[i];
	}

	/**
	 * 判断当前线程中是否保存事物id信息
	 * 
	 * @Title: isValid
	 * @return
	 * @author lkc
	 */
	private static boolean isValid() {
		return getTransactionIdThreadLocal() != null;
	}

	/**
	 * 设置事物id
	 * 
	 * @Title: setTransactionIdThreadLocal
	 * @param transactionId
	 * @author lkc
	 */
	public static void setTransactionIdThreadLocal(String transactionId) {
		setValue(TID_KEY, transactionId, true);
	}

	/**
	 * 获取事物id
	 * 
	 * @Title: getTransactionIdThreadLocal
	 * @author lkc
	 */
	public static String getTransactionIdThreadLocal() {
		return getValue(TID_KEY);
	}

	/**
	 * 获取http计数器
	 * 
	 * @Title: getHttpCount
	 * @return
	 * @author lkc
	 */
	public static String getHttpCount() {
		// 如果当前事物id无效
		if (!isValid()) {
			return HTTP_COUNT_EMPTY;
		}
		Integer count = getValue(HTTP_COUNT_KEY);
		if (count == null) {
			count = 1;
		} else {
			count++;
		}
		setValue(HTTP_COUNT_KEY, count);
		return String.format("%04d", count);
	}

	/**
	 * 清除当前线程事务id
	 */
	public static void cleanTransactionIdThreadLocal() {
		logThreadLocal.set(null);
	}

}